package com.example.service.impl;

import com.example.common.Page;
import com.example.common.PageQueryParam;
import com.example.dao.TUserMapper;
import com.example.entity.TUserEntity;
import com.example.service.TUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.List;


@Service("tUserService")
public class TUserServiceImpl implements TUserService {

    @Autowired
    private TUserMapper tUserMapper;

    @Override
    public List<TUserEntity> selectAll() {
        return tUserMapper.selectAll(new TUserEntity());
    }

    @Override
    public Integer loginChecking(TUserEntity user,
                                 HttpServletResponse response) {

        List<TUserEntity> users = tUserMapper.selectAll(user);
//        Cookie cookie = null;
//        try {
//            cookie = new Cookie("username",
//                    URLEncoder.encode(users.get(0).getUsername(),
//                            "UTF-8"));
//            cookie.setPath("/");
//            cookie.setDomain("activate.navicat.com");
//            cookie.setMaxAge(60*60*24);
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        response.addCookie(cookie);
        if(users.size()>0){
            return users.get(0).getId();
        }else{
            return -1;
        }
    }

    @Override
    public Page<TUserEntity> queryPage(PageQueryParam<TUserEntity> pageQueryParam) {
        List<TUserEntity> rows = tUserMapper.queryPage(pageQueryParam);
        Integer total = tUserMapper.selectCount(pageQueryParam.getParam());
        Page<TUserEntity> page = new Page<>();
        page.setTotal(total);
        page.setRows(rows);
        return page;
    }

    @Override
    public void delete(Integer id) {
        tUserMapper.delete(id);
    }

    @Override
    public void create(TUserEntity userEntity) {
        TUserEntity userEntity1 = new TUserEntity();
        userEntity1.setUsername(userEntity.getUsername());
        List<TUserEntity> tUserEntities = tUserMapper.selectAll(userEntity1);
        if (tUserEntities!=null&&tUserEntities.size()>0){
            throw new RuntimeException("用户名已注册");
        }
        tUserMapper.create(userEntity);
    }
}